package com.example.offer;

import com.example.structure.ListNode;

/**
 * 剑指 Offer 18. 删除链表的节点
 * 给定单向链表的头指针和一个要删除的节点的值，定义一个函数删除该节点。
 * <p>
 * 返回删除后的链表的头节点。
 * <p>
 * 注意：此题对比原题有改动
 * <p>
 * 示例 1:
 * <p>
 * 输入: head = [4,5,1,9], val = 5
 * 输出: [4,1,9]
 * 解释: 给定你链表中值为 5 的第二个节点，那么在调用了你的函数之后，该链表应变为 4 -> 1 -> 9.
 * 示例 2:
 * <p>
 * 输入: head = [4,5,1,9], val = 1
 * 输出: [4,5,9]
 * 解释: 给定你链表中值为 1 的第三个节点，那么在调用了你的函数之后，该链表应变为 4 -> 5 -> 9.
 */
public class DeleteListNode {
    public ListNode deleteNode(ListNode head, int val) {
        //dummy用于返回
        ListNode dummy = new ListNode(1);
        dummy.next = head;
        //用于记录值为val的前面的节点
        ListNode pre = dummy;
        while (head.next != null) {
            if (head.val == val) {
                pre.next = head.next;
                return dummy.next;
            } else {
                head = head.next;
                pre = pre.next;
            }
        }
        if (head.val == val) {
            pre.next = null;
        }
        return dummy.next;
    }

    //精简版
    public ListNode deleteNode2(ListNode head, int val) {
        //dummy用于返回
        ListNode dummy = new ListNode(1);
        dummy.next = head;
        //用于记录值为val的前面的节点
        ListNode pre = dummy;
        while (head.next != null && head.val != val) {
            head = head.next;
            pre = pre.next;
        }
        if (head.next == null) {
            pre.next = null;
        } else {
            pre.next = head.next;
        }
        return dummy.next;
    }
}

class getKthFromEnd {
    public static void main(String[] args) {
        ListNode listNode = new ListNode(3);
        listNode.next = new ListNode(4);
        listNode.next.next = new ListNode(74);
        listNode.next.next.next = new ListNode(84);
        getKthFromEnd getKthFromEnd = new getKthFromEnd();
        getKthFromEnd.getKthFromEnd(listNode, 2);
    }

    public ListNode getKthFromEnd(ListNode head, int k) {
        ListNode pre = head;
        for (int i = 1; i < k; i++) {
            pre = pre.next;
        }
        while (pre.next != null) {
            pre = pre.next;
            head = head.next;
        }
        return head;
    }
}


